import 'package:flutter/widgets.dart';
import 'package:flutter_changdian_football/api/req/ali/req_ali.dart';
import 'package:flutter_changdian_football/pages/mine/my_purse/my_purse_controller.dart';
import 'package:flutter_changdian_football/utils/custom_constant.dart';
import 'package:flutter_changdian_football/widget/dialog/operational_results_dialog.dart';
import 'package:flutter_changdian_football/widget/toast/custom_toast.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:tobias/tobias.dart' as tobias;

class RechargeController extends GetxController {

  RechargeController({
    this.clubId
  });

  final String? clubId;

  int selectCzSeIndex = 0;
  changeCzSeIndex(p) {
    selectCzSeIndex = p;
    update();
  }


  TextEditingController rechargeBalanceController = TextEditingController();

  /// 立即充值
  rechargeNow(type) async {
    if (selectCzSeIndex == 3) {
      if (rechargeBalanceController.text.trim() == '') {
        CustomToast.showTextToast('请输入充值金额');
        return ;
      }
    }

    try {
      EasyLoading.show();
      var resp = await ReqAli.zfbPay(
        businessType: type == CustomConstant.recharge_normal ? 'PERSONAL_RECHARGE' : 'CLUB_RECHARGE', 
        payAmount: selectCzSeIndex == 0 ? '20' : selectCzSeIndex == 1 ? '50' : selectCzSeIndex == 2 ? '100' : rechargeBalanceController.text,
        clubId: clubId,
      );

      if (resp.data['code'] == '200') {
        toAliPay(resp.data['data']);
      } else {
        CustomToast.showTextToast(resp.data['msg']);
      }
    } catch (e) {
      CustomToast.showTextToast('系统繁忙，请稍后再试！');
    } finally {
      EasyLoading.dismiss();
    }

  }

  toAliPay(payInfo) async {
    var result = await tobias.isAliPayInstalled();
    if (result) {
      tobias.aliPay(payInfo).then((value) {
        if (int.parse(value['resultStatus']) == 9000) {
          OperationalResultsDialog.show(
            Get.context!,
            text: '充值成功',
            icon: 'assets/images/img_tc_cg.png',
            confirmTap: () {
              MyPurseController.to.getUserAccountBalance();
              Get.back();
            }
          );
        } else {
          OperationalResultsDialog.show(
            Get.context!,
            text: '充值失败',
            icon: 'assets/images/img_tc_sb.png',
            confirmTap: () {
              Get.back();
            }
          );
        }
      });
    } else {
      CustomToast.showTextToast('请先安装支付宝');
    }
  }

}